<template>
  <div class="home overflowY">
    <div class="PageContent" v-loading="loading">
      <el-form
        :model="ruleForm"
        :inline="true"
        ref="ruleForm"
        :rules="rules"
        class="demo-ruleForm"
        @submit.native.prevent
        label-width="200px"
      >
        <div class="PageItem">
          <el-row class="PageInfo">
            <i class="info-bar"></i>基本信息
          </el-row>
          <el-row class="paddingleft2em">
            <el-form-item label="　付款人（付款单位）" prop="payerName">
              <el-input v-model="ruleForm.payerName" placeholder="请输入付款人姓名" maxlength="50"></el-input>
            </el-form-item>
            <el-form-item label="　　关联逝者编号">
              <el-input v-model="ruleForm.businessCode" placeholder="请输入逝者编号姓名" maxlength="20"></el-input>
            </el-form-item>
            <el-form-item label="　　关联逝者姓名">
              <el-input v-model="ruleForm.deadName" placeholder="请输入逝者姓名" maxlength="20"></el-input>
            </el-form-item>
          </el-row>
          <el-row>
              <el-form-item  label="　　　备注" label-width="200px">
                <el-input v-model="ruleForm.remark" placeholder="请输入备注" style="width: 1000px" maxlength="50"></el-input>
              </el-form-item>
          </el-row>
        </div>
        <div class="PageItem" v-if="true">
          <el-row class="PageInfo">
            <i class="info-bar"></i>零售物品选择
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="tablewrapper">
                <div class="table">
                  <div class="title">
                    <span>零售物品、服务</span>
                  </div>
                  <el-table :data="tableData" style="width: 100%" border>
                    <el-table-column prop="itemName" label="收费项目" width="180"></el-table-column>
                    <el-table-column prop="itemPrice" label="单价" width="100">
                      <template slot-scope="scope" style="width:50px">
                        <input
                          type="text"
                          v-model="scope.row.itemPrice"
                          style="width:80%;height:80%;border:1px solid #dee"
                          :readonly="!!scope.row.asFixPrice"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column prop="itemNumber" label="数量">
                      <template slot-scope="scope" >
                        <input type="text"
                               v-model="scope.row.itemNumber"
                               style="width: 80%;height: 80%;border: 1px solid #dee"
                               
                               />
                      </template>
                    </el-table-column>
                    <el-table-column prop="itemUnit" label="单位"></el-table-column>
                    <el-table-column prop="discountCharge" label="优惠">
                      <template slot-scope="scope">
                        <input type="text"
                               v-model="scope.row.discountCharge"
                               style="width: 80%;height: 80%;border: 1px solid #dee"
                               />
                      </template>
                    </el-table-column>
                    <el-table-column prop="address" label="总金额">
                      <template slot-scope="scope">
                        <span
                          style="margin-left: 10px"
                        >{{TotalAmount(scope.row.itemPrice,scope.row.itemNumber,scope.row.discountCharge) }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column prop="itemSurplusNum" label="物品剩余"></el-table-column>
                    <el-table-column prop="address" label="操作">
                      <template slot-scope="scope">
                        <el-button size="mini" type="text" @click="AddCarItems(scope)">添加</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
              <el-form-item label="　 ">
                <el-input
                  v-model="searchtext"
                  maxlength="50"
                  class="w50"
                  placeholder="输入收费项目名称或简写快速检索"
                ></el-input>
              </el-form-item>
              <!-- <el-button @click="search">搜索</el-button> -->
            </el-col>
            <el-col :span="12">
              <div class="tablewrapper">
                <div class="table">
                  <div class="title">
                    <span>已选择零售物品物品、服务</span>
                  </div>
                  <el-table
                    :data="ruleForm.charges.goodsServices"
                    style="width: 100%"
                    border
                    :show-summary="showSum"
                    :summary-method="getSummaries"
                  >
                    <el-table-column prop="itemName" label="收费项目" width="180"></el-table-column>
                    <el-table-column prop="itemPrice" label="单价" width="100">
                      <template slot-scope="scope">
                        <input type="text"
                               v-model="scope.row.itemPrice"
                               style="width: 80%;height: 80%;border: 1px solid #dee"
                               :readonly="!!scope.row.asFixPrice"
                               
                               />
                      </template>
                    </el-table-column>
                    <el-table-column prop="itemNumber" label="数量">
                      <template slot-scope="scope">
                        <input type="text"
                               v-model="scope.row.itemNumber"
                               style="width: 80%;height: 80%;border: 1px solid #dee"
                               />
                      </template>
                    </el-table-column>
                    <el-table-column prop="itemUnit" label="单位"></el-table-column>
                    <el-table-column prop="discountCharge" label="优惠">
                      <template slot-scope="scope">
                        <input type="text"
                               v-model="scope.row.discountCharge"
                               style="width: 80%;height: 80%;border: 1px solid #dee"
                               />
                      </template>
                    </el-table-column>
                    <el-table-column prop="feeAmount" label="总金额">
                      <template slot-scope="scope">
                        <span
                          style="margin-left: 10px"
                        >{{ TotalAmount(scope.row.itemPrice,scope.row.itemNumber,scope.row.discountCharge)}}</span>
                      </template>
                    </el-table-column>
                    <el-table-column prop="address" label="操作">
                      <template slot-scope="scope">
                        <el-button size="mini" @click="DeleteItems(scope)" type="text">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
        <el-row class="PageItem" :gutter="30" style="text-align: right;margin:30px 0;">
          <!-- <el-button type="primary" @click="Save('ruleForm')" :disabled="false" v-loading="false">保存</el-button> -->
          <el-button type="primary" @click="SaveAndService('ruleForm')" :disabled="false">保存并新增</el-button>
          <el-button type="primary" plain @click="SaveAndService('ruleForm','return')">保存并返回列表</el-button>
          <el-button
            type="primary"
            @click="SaveAndService('ruleForm','settlement')"
            :disabled="false"
          >保存并结算</el-button>

          <!-- <el-button type="primary" plain @click="PrintQRcode(ruleForm.id)">打印接运二维码</el-button> -->
        </el-row>
      </el-form>
    </div>
    <div style="width:0px;height:0px; overflow: hidden;">
      <object id="view1" type="application/x-eloamplugin" name="view"></object>
    </div>
  </div>
</template>
<script>
import * as Type from "@/api/service";
import * as user from "@/api/user";
export default {
  name: "RetailInfo",
  computed: {
    details() {
      // 判断页面是否从其他页面带过来的id
      if (this.$route.params.id) {
        return true;
      } else {
        return false;
      }
    },
  },
  data() {
    return {
      rules: {
        payerName: [
          { required: true, message: "请输入逝者姓名", trigger: "blur" },
        ],
      },
      loading: false,
      showSum: true,
      ruleForm: {
        version: 0,
        id: 0,
        payerName: "", //付款人
        businessCode: "", //逝者编号
        deadName: "", //逝者姓名
        // recSelItem: [], //已选择随车物品
        // relSelDelete: [], //要删除的随车明细
        charges: {
          //物品服务费用信息
          goodsServices: [],
          deleteIds: [],
        },
      }, //按钮权限
      searchtext: "",
      pickerOptions: [],
      dictionary: {
        dicts: {},
        users: {},
      }, //字典
      onpresscTime: 0, //  阻止短时间内连续点击
      tableData: [],
      callTableData: [],
    };
  },
  watch:{
     'ruleForm.charges.goodsServices':{
       handler(val,oldVal){
          this.ruleForm.charges.goodsServices.forEach((item)=> {
            item.itemCharge=item.itemPrice*item.itemNumber;

          });
      },
      deep:true,
    },
    'searchtext':{
      handler(){
        this.search()
      },
    },
  },
  mounted() {
    if (this.details) {
      this.detailedInformation(this.$route.params.id);
      return;
    }
    Type["LoadRetailBusinessAllLoadData"]({
      id: 0,
    }).then((res) => {
      if (res && res.data) {
        // this.dictionary.recDispatchEnable = false
        console.log(res.data.serviceItems.use_in_retail, 33333333);
        res.data.serviceItems.use_in_retail.forEach((item) => {
          item.itemNumber = parseInt(item.itemNumber);
          item.feeAmount = item.itemNumber * item.itemPrice;
          item.discountCharge = 0;
        }); //金额转换成数字类型
        // 计算总价
        this.tableData = res.data.serviceItems.use_in_retail;
        this.callTableData = res.data.serviceItems.use_in_retail;
      }
    });
  },
  methods: {
    // calcCharge(columns,data){
    //         this.ruleForm.charges.goodsServices.forEach((item)=> {
    //         item.itemCharge=item.itemPrice*item.itemNumber;

    //       });
          
    //       // console.log(JSON.stringify(scope));
    //       //his.getSummaries(columns,data);
    // },
    //预约信息保存方法
    Save(ruleForm) {
      //验证连点
      if (Date.now() - this.onpresscTime > 2000) {
        this.onpresscTime = Date.now();
        console.log(Date.now());
      } else {
        return;
      }
      //提交默认客户端

      //   this.ruleForm.arrivalTime = this.formatDate(
      //     new Date(this.ruleForm.arrivalTime)
      //   ); //时间格式处理
      if (this.details) {
        this.ruleForm.recSelItem.forEach((item) => {
          // recid添加
          item.recId = this.$route.params.id;
        });
      }
      //表单验证
      this.$refs[ruleForm].validate((valid) => {
        if (valid) {
          Type["VehicleAppointment"](this.ruleForm).then((res) => {
            console.log(res, "成功了");
            let { data } = res;
            if (!data) {
              this.$message("保存数据失败");
              return;
            }
            this.ruleForm.id = data.id;
            this.$message({
              message: res.message,
              type: "success",
            });
          });
        }
      });
    },
    SaveAndService(ruleForm, name) {
      if (Date.now() - this.onpresscTime > 1000) {
        this.onpresscTime = Date.now();
        console.log(Date.now());
      } else {
        return;
      }

      if (this.details) {
        this.ruleForm.charges.goodsServices.forEach((item) => {
          // recid添加
          item.recId = this.$route.params.id;
        });
      }
      //表单验证
      this.$refs[ruleForm].validate((valid) => {
        if (valid) {
          Type["SaveRetailBusinessAndCharges"](this.ruleForm).then((res) => {
            let { data } = res;
            if (!data) {
              this.$message("保存数据失败");
              return;
            }
            this.$message({
              message: res.message,
              type: "success",
            });
            console.log(data)
            if (name === "return") {
              this.$router.push("RetailList");
            } else if (name === "settlement") {
              this.$router.push({
                name: "home.retail.RetailSettle",
                params: { retailBusinessCode:data.retailBusinessCode }
              });
            }
          });

          this.ruleForm = {
            version: 0,
            id: 0,
            payerName: "", //付款人
            businessCode: "", //逝者编号
            deadName: "", //逝者姓名
            // recSelItem: [], //已选择随车物品
            // relSelDelete: [], //要删除的随车明细
            charges: {
              //物品服务费用信息
              goodsServices: [],
              deleteIds: [],
            },
          };
        }
      });
    },
    PhotoArchival() {
      //没保存就换路由了
      this.Save("ruleForm");
    },
    search() {
      let callTableData = [];
      if (this.searchtext) {
        var reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
        if (reg.test(this.searchtext) || !isNaN(this.searchtext)) {
          this.callTableData.find((item) => {
            if (item.itemName.indexOf(this.searchtext) > -1) {
              callTableData.push(item);
            }
          });
        } else {
          // console.log();
          this.callTableData.find((item) => {
            if (item.itemNameAbbr.indexOf(this.searchtext) > -1) {
              callTableData.push(item);
            }
          });
        }
        this.tableData = callTableData;
      } else {
        Type["LoadRetailBusinessAllLoadData"]({
          id: 0,
        }).then((res) => {
          if (res && res.data) {
            // this.dictionary.recDispatchEnable = false
            res.data.serviceItems.use_in_retail.forEach((item) => {
              item.itemNumber = parseInt(item.itemNumber);
              item.feeAmount = item.itemNumber * item.itemPrice;
              item.discountCharge = 0;
              console.log(382);
            }); //金额转换成数字类型
            // 计算总价
            this.tableData = res.data.serviceItems.use_in_retail;
            this.callTableData = res.data.serviceItems.use_in_retail;
          }
        });
      }
    },

    detailedInformation(id) {
      Type["LoadRetailBusinessAllLoadData"]({
        id,
      }).then((res) => {
        let { data } = res;
        console.log(data, 99999999);

        this.ruleForm = data.retailBusinessData;

        // data.relSelDelete = [];
        data.retailBusinessData.charges.goodsServices.forEach((item) => {
          item.itemNumber = parseInt(item.itemNumber);
          item.feeAmount = item.itemNumber * item.itemPrice;
          //   item.itemPrice = item.itemPrice.toFixed(2);
          //优惠假数据
          item.discountCharge = 0;
        });

        res.data.serviceItems.use_in_retail.forEach((item) => {
          item.itemNumber = parseInt(item.itemNumber);
          item.feeAmount = item.itemNumber * item.itemPrice;
          item.discountCharge = 0;
        }); //金额转换成数字类型
        // 计算总价

        this.tableData = data.serviceItems.use_in_retail;
        this.callTableData = data.serviceItems.use_in_retail;

        // this.ruleForm = data;
        // 已选择随车辆物品、服务
      });
    },

    AddCarItems(scope) {
      scope.row.feeAmount =
        scope.row.itemPrice * scope.row.itemNumber;
      scope.row.serviceItemId = scope.row.id;
      scope.row.id = 0;

      scope.row.itemCharge = scope.row.itemPrice * scope.row.itemNumber; //项目金额
      scope.row.benefitCharge = 0; //减免金额
      scope.row.realityCharge = 0; //实际收费金额
      //假数据 后台需要 实际用不到
      scope.row.chargeTime = this.formatDate(new Date()); // 费用时间

      this.ruleForm.charges.goodsServices.push(scope.row);
      //添加完成之后恢复列表
      if (!this.searchtext) {
        Type["LoadRetailBusinessAllLoadData"]({
          id: 0,
        }).then((res) => {
          if (res && res.data) {
            // this.dictionary.recDispatchEnable = false
            // console.log(res.data.serviceItems.use_in_retail, 33333333);

            res.data.serviceItems.use_in_retail.forEach((item) => {
              item.itemNumber = parseInt(item.itemNumber);
              item.feeAmount = item.itemNumber * item.itemPrice;
              item.discountCharge = 0;
            }); //金额转换成数字类型
            // 计算总价
            this.tableData = res.data.serviceItems.use_in_retail;
            this.callTableData = res.data.serviceItems.use_in_retail;
          }
        });
      } else {
        this.search();
      }
    },
    DeleteItems(scope) {
      //判断id是否为0
      if (scope.row.id) {
        this.ruleForm.charges.deleteIds.push(scope.row);
      }

      this.ruleForm.charges.goodsServices.splice(scope.$index, 1);
    },
    getSummaries({ columns, data }) {
      const sums = [];
      let sum = null;
      data.forEach((item) => {
        sum += item.itemNumber*item.itemPrice;
      });
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "总计";
          return;
        }
        if (index === 5) {
          sums[index] = sum;
          return;
        }
      });
      //   sums[5] = sums[5].toFixed(2);
      return sums;
    },
    TotalAmount(itemPrice, itemNumber, discountCharge) {
      let a = itemPrice * itemNumber;
      return a.toFixed(2);
    },

    formatDate(value) {
      if (!value) return;
      let date = new Date(value);
      let y = date.getFullYear();
      let MM = date.getMonth() + 1;
      MM = MM < 10 ? "0" + MM : MM;
      let d = date.getDate();
      d = d < 10 ? "0" + d : d;
      let h = date.getHours();
      h = h < 10 ? "0" + h : h;
      let m = date.getMinutes();
      m = m < 10 ? "0" + m : m;
      return y + "-" + MM + "-" + d + " " + h + ":" + m;
    },
  },
};
</script>
<style>
/*.cascader .el-form-item__label{*/
/*width: 9vw!important;*/
/*}*/
.cascader .el-input,
.cascader .select .el-input {
  width: 25.6vw !important;
  min-width: 40px;
}

.lineheight label {
  line-height: 20px !important;
  letter-spacing: 3px;
}

.streetwidth,
.streetwidth input,
.streetwidth .el-input,
.streetwidth .el-select {
  width: 7vw !important;
  min-width: 120px !important;
}

.agewidth,
.agewidth input,
.agewidth .el-input {
  width: 5vw !important;
  min-width: 90px !important;
  overflow: hidden;
}

.input-with-select .el-input-group__prepend {
  background-color: #fff;
}

.PageContent .zm .el-input,
.PageContent .zm .el-select {
  width: 25.6vw;
  min-width: 40px;
}

.marginbottom0 .el-form-item {
  margin-bottom: 0px;
}
.home .el-textarea__inner {
  line-height: 2;
  min-height: 70px !important;
}
.home .el-select .el-input__inner {
  cursor: pointer;
  padding-right: 2px;
  text-align: left;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
<style scoped>
.home {
  color: #606266;
}

.w1230 {
  width: 72.5vw !important;
  min-width: 40px !important;
}

.w425 {
  width: 25.6vw;
  min-width: 40px;
}
.w50 {
  width: 40vw;
}
.letter2 {
  letter-spacing: 5px;
}
.DescriptionOfCharges {
  /* style="width:100vm; */
  widows: 100vm;
  height: 70px;
  background: #f0f0f0;
  border-left: 5px solid #a9c3de;
  padding-top: 20px;
  padding-left: 10px;
}
.DescriptionOfCharges > p {
  /* style="width:100vm; */
  margin-left: 30px;
  margin-top: 5px;
}
/* -------------------- */
.el-row {
  margin-bottom: 20px;
}
.el-col {
  border-radius: 4px;
}
.bg-purple-dark {
  background: #99a9bf;
}
.bg-purple {
  background: #d3dce6;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
</style>
